<template>
  <div class="page">
    <div class="top-container">
      <div class="top-left-container" @click="onRouter">
        <left-outlined />
        <span class="ml10">返回</span>
      </div>
      <div class="top-title">
        AI橡皮擦
      </div>
      <div class="top-right-container">
        <div>
          <span>已上传</span>
          <span class="cl-main">{{ imgList.length }}</span>
          <span>/30</span>
        </div>
        <a-button class="ml10" shape="round" @click="imgList = []">清空列表</a-button>
        <a-upload v-model:file-list="fileList" :showUploadList="false" :action="APIURL + 'fileUpload/file'"
          :headers="headers" @change="handleChange" name="files" multiple>
          <a-button class="ml10" shape="round">继续上传</a-button>
        </a-upload>
        <a-button class="ml10" shape="round" :loading="multiloading" @click="onDownload">全部下载</a-button>
      </div>
    </div>
    <div class="ac-container">
      <div class="ac-item-container" @click="onBackBox" :disabled="boxList && boxList.length > 0">
        <rollback-outlined />
        <span class="ml5"> 撤销</span>
      </div>
      <div class="ac-item-container" @click="onClearBox" :disabled="boxList && boxList.length > 0">
        <undo-outlined />
        <span class="ml5"> 重置</span>
      </div>
      <a-button shape="round" class="ml10" @click="onClear">开始清除</a-button>
    </div>
    <div class="content-contianer">
      <img src="@i/left-arrow.png"
        :style="imgList && imgList[imgIndex - 1] && imgList[imgIndex - 1].imgUrl ? '' : 'cursor:not-allowed;'"
        @click="onLastImg" class="left-arrow">
      <img src="@i/right-arrow.png"
        :style="imgList && imgList[imgIndex + 1] && imgList[imgIndex + 1].imgUrl ? '' : 'cursor:not-allowed;'"
        @click="onNextImg" class="right-arrow">
      <div class="tool-container" v-if="imgList && imgList.length > 0">
        <div class="edit-img-container">
          <canvas @mousedown="startSelection" @mouseup="endSelection" @mousemove="updateEndPosition"
            @mouseleave="endSelection" class="edit-img" id="imgCanvas"></canvas>
          <img :src="imgList[imgIndex].newUrl || imgList[imgIndex].imgUrl" srcset="" ref="imgRef">
        </div>
      </div>
      <div v-show="!imgList || imgList.length < 1" class="upload-button-container">
        <a-upload v-model:file-list="fileList" :showUploadList="false" :action="APIURL + 'fileUpload/file'"
          :headers="headers" @change="handleChange" name="files" multiple>
          <div class="upload-button">
            <plus-outlined style="font-size: 18px;" />
            <span style="font-size: 16px;">上传本地图片</span>
          </div>
        </a-upload>
      </div>
      <div class="imgs-ac-container">
        <div class="g-hover-main-cl g-hover-main-cl-border">
          <div class="arrow-button"
            :style="imgList && imgList[imgIndex - 1] && imgList[imgIndex - 1].imgUrl ? '' : 'cursor:not-allowed;'"
            @click="onLastImg">
            <left-outlined />
          </div>
        </div>
        <div class="imgs-list">
          <div class="img-item" v-for="(item, index) in imgList" :key="index" @click="imgIndex = index"
            :style="index === imgIndex ? 'border: 2px solid #FF6923;' : ''">
            <img :src="item.imgUrl" style="max-width: 76px; max-height: 76px; ">
          </div>
        </div>
        <div class="g-hover-main-cl g-hover-main-cl-border">
          <div class="arrow-button"
            :style="imgList && imgList[imgIndex + 1] && imgList[imgIndex + 1].imgUrl ? '' : 'cursor:not-allowed;'"
            @click="onNextImg">
            <right-outlined />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { APIURL, IMGURL } from '@g/data'
import { LeftOutlined, RightOutlined, RollbackOutlined, UndoOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { ref, onMounted, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadChangeParam } from 'ant-design-vue';
import { removeChinaPhoto } from '@r/api/image'
let fileList = ref<any[]>([])
let imgList = ref<any[]>([])
let boxList = ref<any[]>([
])
import { useDownload } from './size/useDownload'
const { finishCount, multiloading, onMultiDownload } = useDownload()
const imgRef = ref()
const imgIndex = ref(0)
const XY = ref<any>({
  startX: null, // 记录开始点击时的x坐标
  startY: null, // 记录开始点击时的y坐标
  endX: null,   // 记录结束点击时的x坐标
  endY: null,
  isMove: false
})
const headers = {
  token: localStorage.getItem('token')
}
import { useRouter, useRoute } from "vue-router";
const appRouter = useRouter()
const selectId = ref<number | undefined>(0)
function onRouter() {
  appRouter.push({
    path: '/product'
  })
}
function onNextImg() {
  if (imgList.value && imgList.value[imgIndex.value + 1] && imgList.value[imgIndex.value + 1].imgUrl) {
    imgIndex.value = imgIndex.value + 1
  }
}
function onLastImg() {
  if (imgList.value && imgList.value[imgIndex.value - 1] && imgList.value[imgIndex.value - 1].imgUrl) {
    imgIndex.value = imgIndex.value - 1
  }
}
function handleChange(info: UploadChangeParam) {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    if (imgList.value.length > 29) {
      message.warn(`一次最多出来30张图片`);
      return
    }
    if (info.file.response.code === 4011) {
      message.warn('请先登录')
      return
    }
    console.log(info.file.response.content.files[0]);
    let url = info.file.response.content.files[0]
    message.success(`${info.file.name} 上传成功`);
    console.log(fileList.value);
    imgList.value = [...imgList.value, {
      imgUrl: IMGURL + url,
      XY: []
    }]
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
}
// 绘制
function onRender() {
  // console.log(, 1111);
  var canvas = document.getElementById('imgCanvas');
  var ctx = canvas?.getContext("2d");
  canvas.width = imgRef.value.offsetWidth
  canvas.height = imgRef.value.offsetHeight
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.strokeStyle = "#FF6923";
  console.log(ctx);
  ctx.lineWidth = 2;
  // item: any
  boxList.value.map((item: any) => {
    ctx.strokeRect(item.x, item.y, item.width, item.height); // 绘制矩形边框				
  })
  // ctx.strokeRect(10, 10, 10, 10); // 绘制矩形边框	
  // ctx.strokeRect(75, 25, 150, 100);
  // ctx.strokeRect(0, 0, 10, 10);
}
function onBackBox() {
  if (boxList.value.length < 1) {
    boxList.value = []
    return
  }
  boxList.value.splice(boxList.value.length - 1, 1)
  onRender()
}
function onClearBox() {
  boxList.value = []
  onRender()
}
function onClear() {
  const item = imgList.value[imgIndex.value]
  removeChinaPhoto({ imageUrl: item.newUrl || item.imgUrl, wordCoordinateList: boxList.value }).then((res: any) => {
    onClearBox()
    imgList.value[imgIndex.value].newUrl = res.outUrl
  })
}
function outEndPosition() {
  if (boxList.value[boxList.value.length - 1] && boxList.value[boxList.value.length - 1].isChange) {
    boxList.value.splice(boxList.value.length - 1, 1)
  }
}
function updateEndPosition(event: any) {
  if (!XY.value.isMove) {
    return
  }
  XY.value.endX = event.offsetX;
  XY.value.endY = event.offsetY;
  // const item = imgList.value[imgIndex.value]
  const selectionWidth = Math.abs(XY.value.endX - XY.value.startX);
  const selectionHeight = Math.abs(XY.value.endY - XY.value.startY);
  let top = XY.value.endY > XY.value.startY ? XY.value.startY : XY.value.endY
  let left = XY.value.endX > XY.value.startX ? XY.value.startX : XY.value.endX
  boxList.value[boxList.value.length - 1] = {
    height: selectionHeight,
    width: selectionWidth,
    x: left,
    y: top,
    isChange: true
  }
  onRender()
}
function mouseleave(event: any) {
  console.log(event);
  console.log(11111);
  if (boxList.value.length < 1) {
    return
  }
  if (boxList.value[boxList.value.length - 1].isChange) {
    console.log(2222);
    boxList.value.splice(boxList.value.length - 1, 1)
  }
  onRender()
}
function endSelection(event: any) {
  if (boxList.value.length < 1) {
    return
  }
  if (!boxList.value[boxList.value.length - 1].isChange) {
    return
  }
  // imgRef.value.offsetWidth
  XY.value.endX = event.offsetX < 0 ? 0 : event.offsetX > imgRef.value.offsetWidth ? imgRef.value.offsetWidth : event.offsetX
  XY.value.endY = event.offsetY < 0 ? 0 : event.offsetY > imgRef.value.offsetHeight ? imgRef.value.offsetHeight : event.offsetY
  XY.value.isMove = false
  const selectionWidth = Math.abs(XY.value.endX - XY.value.startX);
  const selectionHeight = Math.abs(XY.value.endY - XY.value.startY);
  console.log(`框选区域大小为 ${selectionWidth} x ${selectionHeight}`);
  console.log(`开始 ${XY.value.startX} , ${XY.value.startY}`);
  console.log(`结束 ${XY.value.endX} , ${XY.value.endY}`);
  let top = XY.value.endY > XY.value.startY ? XY.value.startY : XY.value.endY
  let left = XY.value.endX > XY.value.startX ? XY.value.startX : XY.value.endX
  boxList.value[boxList.value.length - 1] = {
    height: selectionHeight,
    width: selectionWidth,
    x: left,
    y: top,
    isChange: false
  }
  boxList.value = boxList.value.filter(item => {
    return item.height !== 0 && item.width !== 0
  })
  onRender()
}
function startSelection(event: any) {
  console.log(event);
  XY.value.startX = event.offsetX;
  XY.value.startY = event.offsetY;
  XY.value.isMove = true
  boxList.value = [...boxList.value, {
    height: 0,
    width: 0,
    x: event.offsetX,
    y: event.offsetY,
    isChange: true
  }]
  console.log(boxList.value);
  // document.addEventListener('mouseup', endSelection);
  // document.addEventListener('mousemove', updateEndPosition);

}
const onDownload = () => {
  // 文件数量限制
  // if (fileLength.value > MAXFILELENGTH) {
  //   message.warn('已超出文件数量上限')
  //   return
  // }
  const imagePaths = imgList.value.map(item => item.newUrl || item.imgUrl)
  onMultiDownload(imagePaths)
  // zoomImgs({
  //   width: width.value,
  //   height: height.value,
  //   imagePaths
  // }).then((res: any) => {
  //   onMultiDownload(res)
  // })
}
onMounted(() => {
  // getList()
  // getTypeList()
})
</script>

<style scoped lang="less">
.cl-main {
  color: #FF6923;
}

.page {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  align-items: center;
}

.top-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  align-items: center;
  width: 100%;
  height: 44px;
  opacity: 1;
  background: #FAFAFA;
  box-shadow: inset 0px -1px 0px 0px #EFEFEF;
  padding: 0 12px;
  position: relative;

  .top-left-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    cursor: pointer;
    color: #333;
    font-size: 14px;
  }

  .top-title {
    font-size: 14px;
    font-weight: 500;
    line-height: 14px;
    text-align: center;
    letter-spacing: 0em;
    color: #333333;
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    width: fit-content;
  }

  .top-right-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 14px;
    line-height: 14px;
    letter-spacing: 0px;
    font-weight: 400;
    font-size: 14;
    color: #666666
  }
}

.ac-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 44px;
  opacity: 1;
  background: #FFFFFF;

  .ac-item-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 16px;
    margin-left: 15px;
    cursor: pointer;
  }
}

.ac-container :hover {
  color: #FF6923;
}

// .box-button {
//   width: 74px;
//   height: 32px;
//   border-radius: 4px;
//   opacity: 1;
//   background: rgba(255, 235, 221, 0.4);
//   display: flex;
//   flex-direction: row;
//   align-items: center;
// }

.upload-button {
  height: 500px;
  width: 500px;
  border-radius: 10px;
  border: 1px solid #DCDCDC;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-button-container {
  margin-top: 30px;
  border-radius: 10px;
}

.upload-button-container :hover .upload-button {
  border: 1px dashed #FF6923;
  color: #FF6923;
}

.upload-button :hover {
  color: #FF6923;
}

.content-contianer {
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
  align-items: center;

  .left-arrow {
    height: 40px;
    width: 40px;
    cursor: pointer;
    top: calc(50% - 20px);
    left: 10px;
    position: absolute;
  }

  .right-arrow {
    height: 40px;
    width: 40px;
    cursor: pointer;
    top: calc(50% - 20px);
    right: 10px;
    position: absolute;
  }
}

.imgs-ac-container {
  display: flex;
  flex-direction: row;
  height: 110px;
  padding: 16px;
  width: 100%;
  background-color: #fff;
  align-items: center;
  margin-top: 20px;

  .arrow-button {
    width: 24px;
    height: 80px;
    border-radius: 4px;
    opacity: 1;
    background: #FFFFFF;
    box-sizing: border-box;
    border: 1px solid #DCDCDC;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  .imgs-list {
    flex: 1;
    overflow-x: auto;
    display: flex;
    flex-direction: row;
    padding: 0 7px;
  }

  .img-item {
    height: 80px;
    width: 80px;
    border: 1px solid #DCDCDC;
    margin: 0 7px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #FFFFFF;
    border-radius: 4px;
    cursor: pointer;
  }
}

.tool-container {
  // width: 900px;
  // height: 900px;
  // overflow: scroll;
  // overflow-x: scroll;
  // overflow-y: scroll;
  margin-top: 30px;
  border: 1px solid #ccc;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;

  .edit-img-container {
    // height: 100%;
    // width: 100%;
    position: relative;
  }

  .edit-img {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .box {
    position: absolute;
    z-index: 2;
    border: 3px dashed #FF6923;
  }
}
</style>